//
//  ViewController.m
//  代码创建UICollectionView
//
//  Created by 陈家庆 on 15-2-6.
//  Copyright (c) 2015年 shikee_Chan. All rights reserved.
//

#import "ViewController.h"
#import "CollectionViewCell.h"
#import "MyView.h"
#define fDeviceWidth [[UIScreen mainScreen] bounds].size.width
#define fDeviceHeight [[UIScreen mainScreen] bounds].size.height

@interface ViewController ()<UIScrollViewDelegate>
@property (nonatomic,strong) UIScrollView *scrollView11;

@property (nonatomic, assign)NSInteger picWidth;

@property (nonatomic, assign)NSInteger picHeight;

@property (nonatomic, assign)NSInteger picNum;

@property (nonatomic, retain)NSTimer *timer;

@property (nonatomic, assign)NSInteger currentPage;

@property(nonatomic,strong)UISearchBar *customSearchBar;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
//    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0/255.0f green:128/255.0f blue:255/255.0f alpha:1];//不能放init处
//    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
//    self.navigationController.navigationBarHidden=NO;
    self.navigationItem.title = @"自定义collectionView";
    
    float AD_height = fDeviceHeight*0.7;//广告栏高度
    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    flowLayout.headerReferenceSize = CGSizeMake(fDeviceWidth, AD_height+10);//头部
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, fDeviceWidth, fDeviceHeight) collectionViewLayout:flowLayout];
    
    //设置代理
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
    
    
    
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    //注册cell和ReusableView（相当于头部）
    [self.collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"ReusableView"];
    
    
    /*
     ***广告栏
     */
    MyView *my = [MyView one];
    my.frame = CGRectMake(5, 5, fDeviceWidth-10, AD_height);
    _headerView = my;
    
    self.scrollView11 = my.myScrollView;
    self.scrollView11.delegate = self;
    
    
    self.picWidth=375;
    self.picHeight=200;
    self.picNum=5;
    
    for (int i=0; i<self.picNum; i++) {
        CGFloat px=i*self.picWidth;
        
        NSString *path=[NSString stringWithFormat:@"%d.jpg",i+1];
        
        UIImageView *pic=[[UIImageView alloc]initWithFrame:CGRectMake(px, 0, self.picWidth, self.picHeight)];
        
        pic.image=[UIImage imageNamed:path];
        
        [self.scrollView11 addSubview:pic];
    }
    self.scrollView11.contentSize=CGSizeMake(self.picNum*self.picWidth, 0);
    
    self.scrollView11.pagingEnabled=YES;
    
    [self startTimer];
    
    [[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
    
}
//

/**
 *  开启定时器
 */
- (void)startTimer{
    self.timer=[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(changePic) userInfo:@"" repeats:YES];
}
/**
 *  定时器每秒触发 切换图片
 */
- (void)changePic{
    NSInteger index=self.currentPage;
    
    if (index==self.picNum-1) {
        //        self.scrollerView.contentOffset=CGPointZero;
        [self.scrollView11 setContentOffset:CGPointZero animated:YES];
        
    }
    else {
        index++;
        //self.scrollerView.contentOffset=CGPointMake(self.picWidth*index,0);
        
        [self.scrollView11 setContentOffset: CGPointMake(self.picWidth*index,0)animated:YES];//添加动画
    }
    
}
/**
 *  移除定时器
 */
- (void)removeMyTimer{
    if (self.timer!=nil) {
        [self.timer invalidate];
        self.timer=nil;
    }
}
/**
 *  滑动scorllView触发
 *
 *
 */

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat width=scrollView.contentOffset.x;
    
    self.currentPage=width/self.picWidth;
    
}

/**
 *  开始拖拽时移除定时器
 *
 *  @param scrollView
 */
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self removeMyTimer];
}
/**
 *
 *停止拖拽时启动定时器
 */
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    [self startTimer];
}


#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 30;
}
//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identify = @"cell";
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
    [cell sizeToFit];
    if (!cell) {
        NSLog(@"无法创建CollectionViewCell时打印，自定义的cell就不可能进来了。");
    }
    cell.imgView.image = [UIImage imageNamed:@"pic1.jpg"];
    cell.text.text = [NSString stringWithFormat:@"iPhone6s"];
    cell.btn.text = @"￥888";
    cell.text1.text = @"月售:10件";
    [cell.text1 sizeToFit];
    cell.text1.adjustsFontSizeToFitWidth=YES;
    
    return cell;
}
//头部显示的内容
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:
                                            UICollectionElementKindSectionHeader withReuseIdentifier:@"ReusableView" forIndexPath:indexPath];
    
    [headerView addSubview:_headerView];//头部广告栏
    return headerView;
}
#pragma mark --UICollectionViewDelegateFlowLayout
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //边距占5*4=20 ，2个
    //图片为正方形，边长：(fDeviceWidth-20)/2-5-5 所以总高(fDeviceWidth-20)/2-5-5 +20+30+5+5 label高20 btn高30 边
    return CGSizeMake((fDeviceWidth-20)/2, (fDeviceWidth-20)/2+50);
}
//定义每个UICollectionView 的间距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 5, 5, 5);
}
//定义每个UICollectionView 纵向的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}
#pragma mark --UICollectionViewDelegate
//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    //    UICollectionViewCell * cell = (UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    //    cell.backgroundColor = [UIColor redColor];
    NSLog(@"选择%ld",indexPath.row);
}
//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
